package org.codingeasy.streamrecord.examples.expression;

import com.alibaba.fastjson.JSONObject;
import java.util.stream.Collectors;
import org.codingeasy.streamrecord.core.CurrentContext;
import org.codingeasy.streamrecord.core.DefaultRecordProducer;
import org.codingeasy.streamrecord.core.Pipeline;
import org.codingeasy.streamrecord.core.RecordProducer;
import org.codingeasy.streamrecord.core.matedata.RecordInfoWrapper;
import org.codingeasy.streamrecord.examples.service.UserService;
import org.codingeasy.streamrecord.examples.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
*   
* @author : KangNing Hu
*/

@Configuration
public class Config {

  private Logger logger = LoggerFactory.getLogger(Config.class);

  /**
   * 自定义一个全局的默认管道
   * @return
   */
  @Bean
  public Pipeline defaultPipeline() {
    return auditLogInfoWrapper -> {
      //如果是多个结果
      if (auditLogInfoWrapper.isMultiple()) {
        logger.info("管道中已有多个结果:{}", JSONObject.toJSONString(auditLogInfoWrapper.getRecordInfos()));
      }
      //如果只有一个结果
      else {
        logger.info("管道中已有多个结果:{}", JSONObject.toJSONString(auditLogInfoWrapper.getRecordInfo()));
      }
    };
  }



  /**
   * 自定义一个全局日志生成器
   * @return
   */
  @Bean
  public RecordProducer defaultProducer() {
    return new DefaultRecordProducer() {
      @Override
      public RecordInfoWrapper doProduce(CurrentContext currentContext) {
        try {

          System.out.printf("日志的属性参数 %s", currentContext.getAttributeAccess()
              .entrySet().stream().map(item -> item.getKey() + ":" + item.getValue())
              .collect(Collectors.joining(",")));
          System.out.println(String.format("执行时长：%s", currentContext.getDuration()));
        } catch (Exception e) {
          e.printStackTrace();
        }
        return super.doProduce(currentContext);
      }
    };
  }


  @Bean
  public UserService userService() {
    return new UserServiceImpl();
  }

}
